package org.jeecg.modules.system.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.service.IJournalService;
import org.jeecg.modules.system.service.ISysDictItemService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@RestController
@RequestMapping("/journal")
@Api(tags="报表")
@Slf4j
public class JournalController {

    @Autowired
    private IJournalService journalService;

    @Autowired
    private ISysDictItemService sysDictItemService;

    @ApiOperation(value = "查询耗电量", notes = "返回状态为未删除的设备耗电量")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<List> queryList(@RequestParam(name="startDate") String startDate,
                                     @RequestParam(name="endDate") String endDate,
                                     @RequestParam(name="type") String type,
                                     @RequestParam(name="siteId",required = false) String siteId,HttpServletRequest req) {
        Result<List> result = new Result<List>();
        result.setSuccess(true);
        result.setResult(journalService.getReportData(startDate,endDate,type,siteId));
        return result;
    }

    @ApiOperation(value = "查询耗电量", notes = "返回站点耗电量")
    @RequestMapping(value = "/listSite", method = RequestMethod.GET)
    public Result<List> querySiteList(@RequestParam(name="startDate") String startDate,
                                     @RequestParam(name="endDate") String endDate,
                                     @RequestParam(name="type") String type,
                                     @RequestParam(name="siteId",required = false) String siteId,HttpServletRequest req) {
        Result<List> result = new Result<List>();
        result.setSuccess(true);
        result.setResult(journalService.getSiteReportData(startDate,endDate,type,siteId));
        return result;
    }

    @ApiOperation(value = "导出耗电量", notes = "返回站点耗电量excel")
    @RequestMapping(value = "/listSiteExport", method = RequestMethod.GET)
    public ModelAndView exportSiteList(@RequestParam(name="startDate") String startDate,
                                       @RequestParam(name="endDate") String endDate,
                                       @RequestParam(name="type") String type,
                                       @RequestParam(name="siteId",required = false) String siteId, HttpServletRequest req) {
        List<Map<?,?>> siteData = journalService.getSiteReportData(startDate,endDate,type,siteId);
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());

        mv.addObject(NormalExcelConstants.FILE_NAME, "导出能耗量");
        mv.addObject(NormalExcelConstants.CLASS, SitePowerEntity.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("导出能耗量清单", "导出人:"+user.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, siteData.get(0).get("meterData"));
        return mv;
    }

    @ApiOperation(value = "查询耗电量", notes = "返回设备耗电量")
    @RequestMapping(value = "/listEq", method = RequestMethod.GET)
    public Result<List> queryEqList(@RequestParam(name="startDate") String startDate,
                                      @RequestParam(name="endDate") String endDate,
                                      @RequestParam(name="type") String type,
                                      @RequestParam(name="eqId",required = false) String eqId,HttpServletRequest req) {
        Result<List> result = new Result<List>();
        result.setSuccess(true);
        result.setResult(journalService.getEqReportData(startDate,endDate,type,eqId));
        return result;
    }

    @ApiOperation(value = "根据设备类型返回统计数据", notes = "设备为有效设备，且字典有效")
    @RequestMapping(value = "/listEqTypeCount", method = RequestMethod.GET)
    public Result<List> queryEqTypeCountList(@RequestParam(name="siteId",required = true) String siteId,HttpServletRequest req) {
        Result<List> result = new Result<List>();
        result.setSuccess(true);
        result.setResult(journalService.getEqTypeCount(siteId));
        return result;
    }

    @ApiOperation(value = "设备耗电和发电统计接口", notes = "不区分设备是否有效，都返回")
    @RequestMapping(value = "/queryEqPowerTotal", method = RequestMethod.GET)
    public Result<List> queryEqPowerTotal(@RequestParam(name="startDate") String startDate,
                                          @RequestParam(name="endDate") String endDate,
                                          @RequestParam(name="eqId") String eqId,HttpServletRequest req) {
        Result<List> result = new Result<List>();
        result.setSuccess(true);
        result.setResult(journalService.getEqPowerTotal(startDate,endDate,eqId));
        return result;
    }

    @ApiOperation(value = "设备耗电和发电统计接口", notes = "不区分设备是否有效，都返回")
    @RequestMapping(value = "/queryEqPowerTotalExport", method = RequestMethod.GET)
    public ModelAndView queryEqPowerTotalExport(@RequestParam(name="startDate") String startDate,
                                          @RequestParam(name="endDate") String endDate,
                                          @RequestParam(name="eqId") String eqId,HttpServletRequest req) {
        List eqPowerList = journalService.getEqPowerTotal(startDate,endDate,eqId);

        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());

        mv.addObject(NormalExcelConstants.FILE_NAME, "导出能耗量");
        mv.addObject(NormalExcelConstants.CLASS, EqPowerEntity.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("导出能耗量清单", "导出人:"+user.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, eqPowerList);
        return mv;
    }

    @ApiOperation(value = "设备耗电和发电统计接口", notes = "不区分设备是否有效，都返回")
    @RequestMapping(value = "/queryEqPowerTotalBySite", method = RequestMethod.GET)
    public Result<List> queryEqPowerTotalBySite(@RequestParam(name="startDate") String startDate,
                                          @RequestParam(name="endDate") String endDate,
                                          @RequestParam(name="siteId") String siteId,
                                          @RequestParam(name="sortKey",defaultValue = "power_consumption") String sortKey,
                                          @RequestParam(name="sortType",defaultValue = "desc") String sortType,HttpServletRequest req) {
        Result<List> result = new Result<List>();
        result.setSuccess(true);
        result.setResult(journalService.getEqPowerTotalBySite(startDate,endDate,siteId,sortKey,sortType));
        return result;
    }

    @ApiOperation(value = "设备耗电和发电统计接口", notes = "不区分设备是否有效，都返回")
    @RequestMapping(value = "/queryEqPowerTotalBySiteExport", method = RequestMethod.GET)
    public ModelAndView queryEqPowerTotalBySiteExport(@RequestParam(name="startDate") String startDate,
                                                @RequestParam(name="endDate") String endDate,
                                                @RequestParam(name="siteId") String siteId,
                                                @RequestParam(name="sortKey",defaultValue = "power_consumption") String sortKey,
                                                @RequestParam(name="sortType",defaultValue = "desc") String sortType,HttpServletRequest req) {
        List eqPowerList = journalService.getEqPowerTotalBySite(startDate,endDate,siteId,sortKey,sortType);

        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());

        mv.addObject(NormalExcelConstants.FILE_NAME, "导出能耗量");
        mv.addObject(NormalExcelConstants.CLASS, EqPowerEntity.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("导出能耗量清单", "", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, eqPowerList);
        return mv;
    }

    @ApiOperation(value = "站点耗电发电统计接口", notes = "不区分设备是否有效，都返回")
    @RequestMapping(value = "/querySitePowerTotal", method = RequestMethod.GET)
    public Result<List> querySitePowerTotal(@RequestParam(name="startDate") String startDate,
                                          @RequestParam(name="endDate") String endDate,
                                          @RequestParam(name="siteId") String siteId,HttpServletRequest req) {
        Result<List> result = new Result<List>();
        result.setSuccess(true);

        //这里只取逆变器的发电和耗电
        List<Map<String,Object>> sitePowerTotal = journalService.getSitePowerTotal(startDate,endDate,siteId,"2");
        List<Map<String,Object>> sitePowerTotalWithStandard = new ArrayList<>();

        for(Map<String,Object> m : sitePowerTotal){

            System.out.println("powerGeneration"+m.toString());
            if(m.get("power_generation") == null){
                m.put("bzm",null);
                m.put("tqhhw",null);
                m.put("eyht",null);
                m.put("yc",null);
                m.put("eyhl",null);
                m.put("yyht",null);
                m.put("dyhw",null);
            }else{
                DecimalFormat df = new DecimalFormat("#.###");
                Double powerGeneration = (Double)m.get("power_generation");
                m.put("bzm",df.format(powerGeneration * (3.1/10000)*1*1000*1000)); //标准煤（吨）
                m.put("tqhhw",df.format(powerGeneration * (3.1/10000)*0.005*1000));//碳氢化合物（千克）
                m.put("eyht",df.format(powerGeneration * (3.1/10000)*2.6*1000*1000));//二氧化碳（吨）
                m.put("yc",df.format(powerGeneration * (3.1/10000)*0.011*1000));//烟尘（千克）
                m.put("eyhl",df.format(powerGeneration * (3.1/10000)*0.06*1000));//二氧化硫（千克）
                m.put("yyht",df.format(powerGeneration * (3.1/10000)*0.0227*1000));//一氧化碳（千克）
                m.put("dyhw",df.format(powerGeneration * (3.1/10000)*0.036*1000));//氮氧化物（千克）
            }

            sitePowerTotalWithStandard.add(m);
        }


        result.setResult(sitePowerTotal);
        return result;
    }

    @ApiOperation(value = "站点耗电发电统计接口（返回日月年累计）", notes = "不区分设备是否有效，都返回")
    @RequestMapping(value = "/querySitePowerTotalAllPeriod", method = RequestMethod.GET)
    public Result<List> querySitePowerTotalAllPeriod(@RequestParam(name="siteId") String siteId,HttpServletRequest req) {
        Result<List> result = new Result<List>();
        result.setSuccess(true);

        Map<String,Object> sitePower = new HashMap<>();

        //当日
        String today = DateUtils.formatDate();
        sitePower.put("day",getSitePowerData(today,today,siteId));

        //当月
        Calendar calendar = Calendar.getInstance();
        String firstDayOfMonth = getFisrtDayOfMonth(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH) + 1);
        String endDayOfMonth = getLastDayOfMonth(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH) + 1);
        sitePower.put("month",getSitePowerData(firstDayOfMonth,endDayOfMonth,siteId));

        //当年
        sitePower.put("year",getSitePowerData(calendar.get(Calendar.YEAR)+"-01-01",calendar.get(Calendar.YEAR)+"-12-31",siteId));

        //全部
        sitePower.put("period",getSitePowerData("2020-01-01","2099-01-01",siteId));

        List<Map<String,Object>> sitePowerTotal = new ArrayList<>();
        sitePowerTotal.add(sitePower);

        result.setResult(sitePowerTotal);
        return result;
    }

    private Map<String,Map<String,Object>> getSitePowerData(String startDate,String endDate,String siteId){
        Map<String,Map<String,Object>> powerData = new HashMap<>();
        String today = DateUtils.formatDate();
        List<Map<String,Object>> sitePowerEq2Total = journalService.getSitePowerTotal(startDate,endDate,siteId,"2");
        List<Map<String,Object>> sitePowerEq5Total = journalService.getSitePowerTotal(startDate,endDate,siteId,"5");
        if(sitePowerEq2Total == null) {
            sitePowerEq2Total = sitePowerEq5Total;
        } else if(sitePowerEq5Total != null) {
            //合并两个的发电量数据
            Map<String,Object> eq2 = sitePowerEq2Total.get(0);
            Map<String,Object> eq5 = sitePowerEq5Total.get(0);
            Double powerGeneration = Double.parseDouble("0");
            if(eq2.get("power_generation")!=null){
                powerGeneration = (Double)eq2.get("power_generation");
            }
            if(eq5.get("power_generation")!=null) {
                Double powerGeneration5 = (Double)eq5.get("power_generation");
                powerGeneration += powerGeneration5;
            }
            eq2.put("power_generation", powerGeneration);
        }
        if(sitePowerEq2Total!=null){
            Map<String,Object> eq2 = sitePowerEq2Total.get(0);
            DecimalFormat df = new DecimalFormat("#.###");
            Double powerGeneration = Double.parseDouble("0");
            if(eq2.get("power_generation")!=null){
                powerGeneration = (Double)eq2.get("power_generation");
            }
            eq2.put("bzm",df.format(powerGeneration * (3.1/10000)*1*1000*1000)); //标准煤（吨）
            eq2.put("tqhhw",df.format(powerGeneration * (3.1/10000)*0.005*1000));//碳氢化合物（千克）
            eq2.put("eyht",df.format(powerGeneration * (3.1/10000)*2.6*1000*1000));//二氧化碳（吨）
            eq2.put("yc",df.format(powerGeneration * (3.1/10000)*0.011*1000));//烟尘（千克）
            eq2.put("eyhl",df.format(powerGeneration * (3.1/10000)*0.06*1000));//二氧化硫（千克）
            eq2.put("yyht",df.format(powerGeneration * (3.1/10000)*0.0227*1000));//一氧化碳（千克）
            eq2.put("dyhw",df.format(powerGeneration * (3.1/10000)*0.036*1000));//氮氧化物（千克）
            powerData.put("eq2",eq2);
        }

        List<Map<String,Object>> sitePowerEq3Total = journalService.getSitePowerTotal(startDate,endDate,siteId,"3");
        if(sitePowerEq3Total!=null){
            Map<String,Object> eq3 = sitePowerEq3Total.get(0);
            powerData.put("eq3",eq3);
        }
        return powerData;
    }

    public static String getFisrtDayOfMonth(int year,int month)
    {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最小天数
        int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayOfMonth = sdf.format(cal.getTime());
        return firstDayOfMonth;
    }

    public static String getLastDayOfMonth(int year,int month)
    {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
        return lastDayOfMonth;
    }


    @ApiOperation(value = "查询告警量", notes = "返回告警量")
    @RequestMapping(value = "/listAlarm", method = RequestMethod.GET)
    public Result<List> queryAlarmList(@RequestParam(name="startDate") String startDate,
                                    @RequestParam(name="endDate") String endDate,
                                    @RequestParam(name="type") String type, @RequestParam(name="eqId") String eqId,HttpServletRequest req) {
        Result<List> result = new Result<List>();
        result.setSuccess(true);
        result.setResult(journalService.getAlarmReportData(startDate,endDate,type,eqId));
        return result;
    }

}
